﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OpenComposite.Base.Designer;
using OpenComposite.EII.Designer.Org.Forms;
using OpenComposite.Repository.Properties;
using OpenComposite.EII.Repository;
using OpenComposite.EII.RepositoryUIs;

namespace OpenComposite.EII.Designer.Org
{
	public class UserSymbol : CollapsableSymbol
	{
		public UserSymbol()
			: base()
		{
			init();
		}

		private OpenComposite.Base.Designer.ListView _lvUsers = new OpenComposite.Base.Designer.ListView();
		private ContextMenuStrip _contextListView = new ContextMenuStrip();

		public List<User> Persons
		{
			get
			{
				List<User> list = new List<User>();
				foreach ( Row row in _lvUsers.Rows ) {
					list.Add((User)row.Items[0]);
				}
				return list;
			}
		}

		private string _managerName = "";

		private void init()
		{
			this.BeginUpdate();

			this.Name = "User";
			this.Text = "Persons";

			this.Border = BorderType.RoundedRectangle;
			this.BackBrushMode = BackgroundBrushMode.LinearGradient;
			this.BackLinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical;

			this.NameTextBox.AutoSize = false;
			this.MinimumSize = new Size(160, 50);
			this.AllowDrop = true;

			//context Menu
			//this.ContextMenuStrip.Items.Add("Add Role", Resources.png_users, new EventHandler(onAddRole_Click));

			//collapsing
			this.IsCollapsed = true;
			this.ShowCollapseButton = false; /*collapsed by parent*/
			this.CollapseSign = CollapseSign.DoubleArrow;
			this.CollapseSignPosition = CollapseSignPosition.TopRight;

			this.CollapsedBackColor = Color.BlanchedAlmond;
			this.CollapsedBackColor2 = Color.White;
			this.CollapsedBorderColor = BorderColor;
			this.CollapsedSize = new Size(Size.Width, 50);

			this.ExpandedBackColor = Color.BlanchedAlmond;
			this.ExpandedBackColor2 = Color.White;
			this.ExpandedBorderColor = BorderColor;
			this.ExpandedSize = new Size(Size.Width, 200);

			// lvContext			
			_contextListView.Items.Add("Show Details", Resources.png_list, new EventHandler(onEditUser_Click));
			_contextListView.Items.Add(new ToolStripSeparator());
			_contextListView.Items.Add("Add Person", Resources.png_user, new EventHandler(onAddUser_Click));
			_contextListView.Items.Add("Delete Person", Resources.delete, new EventHandler(onDeleteUser_Click));

			// listview
			_lvUsers.Size = new Size(Width - BorderWidth * 2, Height - 70);
			_lvUsers.Location = new Point(Location.X, Location.Y + 15);
			_lvUsers.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left |
				 System.Windows.Forms.AnchorStyles.Right | System.Windows.Forms.AnchorStyles.Top;
			_lvUsers.Columns.Add(new Column("Name", Column.ColumnType.TextBox));
			_lvUsers.ContextMenuStrip = _contextListView;
			this.Controls.Add(_lvUsers);

			this.EndUpdate();
		}

		public override void InitializeNew(IServiceProvider serviceProvider)
		{
			base.InitializeNew(serviceProvider);
		}

		public override void InitializeLoaded()
		{
			foreach ( User person in Global.Data.GetOrgUsersByOrgUnit(1) ) {
				_lvUsers.Rows.Add(person);
			}
			base.InitializeLoaded();
		}

		#region Public Members

		#region Override
		public override bool CanDrag
		{
			get { return true; }
		}

		public override bool CanResize
		{
			get { return false; }
		}

		public override bool CanSelect
		{
			get { return false; }
		}

		public override bool CanMove
		{
			get { return false; }
		}

		public override bool CanFocused
		{
			get { return false; }
		}

		public override bool IsDropAllowed(object obj, Point location, MouseButtons button)
		{
			return
				( button == MouseButtons.Right &&
				obj is OrgSymbol ||
				obj is OrgUnitSymbol ||
				obj is RoleSymbol ||
				obj is UserSymbol );
		}

		public override bool CheckMouseOver(Point location)
		{
			return base.CheckMouseOver(location);
		}

		public override void DropObject(object obj, Point location, MouseButtons button)
		{
			base.DropObject(obj, location, button);
		}

		public override object GetDragObject(Point location, MouseButtons button)
		{
			return this;
		}

		public override void PaintBackground(PaintEventArgs pe)
		{
			base.PaintBackground(pe);

			Rectangle rc = this.ClientRectangle;
			Point pt = this.PointToDesignerView(new Point(rc.X, rc.Bottom - 16));
			pe.Graphics.DrawImage(Resources.png_user, pt.X, pt.Y);
			pt.Offset(Resources.png_user.Width + 5, 0);
			if ( _lvUsers.Rows.Count > 0 )
				pe.Graphics.DrawString("Manager: " + _lvUsers.Rows[0].Items[0].ToString(), Font, ForeBrush, (PointF)pt);
			else
				pe.Graphics.DrawString("Manager: n/a", Font, ForeBrush, (PointF)pt);
		}

		protected override Rectangle CalculateClientArea()
		{
			Rectangle r = this.Bounds;
			try {
				r.Inflate(-BorderWidth, -BorderWidth);
			} catch { }
			return r;
		}

		#endregion

		public string ManagerName
		{
			get { return _managerName; }
		}

		#endregion

		protected override void OnMouseClick(System.Windows.Forms.MouseEventArgs e)
		{
			base.OnMouseClick(e);
		}

		#region Private Members

		private void onAddRole_Click(object sender, EventArgs e)
		{
			int index = this.DesignerViewControl.AddDesignerControl(new RoleSymbol());
			this.DesignerViewControl.DesignerControls[index].Location =
				new Point(Location.X, Location.Y + Height + 40);
			this.DesignerViewControl.AddRoute(this, DesignerViewControl.DesignerControls[index]);
		}

		private void onAddUser_Click(object sender, EventArgs e)
		{
			RepositoryService rpSvc = (RepositoryService)this.GetService(typeof(RepositoryService));
			if ( rpSvc == null )
				throw new NullReferenceException("Repository Service not available.");

			IRepositoryItem parentItem = null;
			User newEntry = rpSvc.GetNewItem<User>(true, ref parentItem);
			if ( newEntry != null ) {
				lookForManager();
				_lvUsers.Rows.Add(newEntry);
				updateTitle();
			}
		}

		private void onEditUser_Click(object sender, EventArgs e)
		{
			updateTitle();
		}

		private void onDeleteUser_Click(object sender, EventArgs e)
		{
			User toDelete = _lvUsers.Rows[_lvUsers.SelectedIndex].Items[0] as User;
			if ( toDelete.Delete(true) ) {
				_lvUsers.Rows.RemoveAt(_lvUsers.SelectedIndex);
				updateTitle();
			}
		}

		private void lookForManager()
		{
			string name = "n/a";
			foreach ( Row row in _lvUsers.Rows ) {
				User item = row.Items[0] as User;
				foreach ( Role role in item.Roles ) {
					if ( role.Name == "Manager" ) {
						name = item.FormattedName;
						break;
					}
				}

			}
		}

		private void updateTitle()
		{
			this.Text = _lvUsers.Rows.Count.ToString() + ( _lvUsers.Rows.Count == 1 ? " Person" : " Persons" );
			this.Refresh();
		}

		#endregion
	}
}
